let ismousedown = false;

export function turnOnBrush(context) {
  let canvas = context.canvas;
  context.strokeStyle = "#333";

  canvas.addEventListener("mousedown", drawRect);

  canvas.addEventListener("mouseup", mouseup);

  let start = {};

  function drawRect(e) {
    ismousedown = true;
    start = convertPos(e.x, e.y);
    context.beginPath();
    context.moveTo(start.x, start.y);
    canvas.addEventListener("mousemove", mousemove);
  }

  function mousemove(e) {
    let target = convertPos(e.x, e.y);
    if (ismousedown) {
      context.lineTo(target.x, target.y);
      context.stroke();
    }
  }

  function mouseup(e) {
    this.ismousedown = false;
    // canvas.removeEventListener(drawRect);
    canvas.removeEventListener("mousemove", mousemove);
  }

  function convertPos(x, y) {
    let box = canvas.getBoundingClientRect();

    return {
      x: x - (box.left * canvas.width) / box.width,
      y: y - (box.top * canvas.height) / box.height,
    };
  }
}
